﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
using Furion.RemoteRequest.Extensions;
using Microsoft.AspNetCore.Authorization;
using Serilog;
using HttpMethod = System.Net.Http.HttpMethod;
using Furion;
using NetTopologySuite.Algorithm.Locate;
using Furion.DataValidation;

namespace Admin.NET.Application
{
    /// <summary>
    /// 报检单
    /// </summary>
    [ApiDescriptionSettings("报检单", Name = "WmsInspectOrder", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsInspectOrderService : IWmsInspectOrderService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsOrder,MasterDbContextLocator> _wmsOrderRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wmsOrderTypeRep;
        private readonly IRepository<WmsOrderDetails, MasterDbContextLocator> _wmsOrderDetailsRep;
        private readonly IRepository<WmsPlace, MasterDbContextLocator> _wmsPlaceRep;
        private readonly IRepository<WmsReceiptOrder, MasterDbContextLocator> _wmsReceiptOrderRep;

        public WmsInspectOrderService(
            IRepository<WmsOrder,MasterDbContextLocator> wmsOrderRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
            ,IRepository<WmsOrderType, MasterDbContextLocator> wmsOrderTypeRep
            ,IRepository<WmsOrderDetails, MasterDbContextLocator> wmsOrderDetailsRep
            ,IRepository<WmsPlace, MasterDbContextLocator> wmsPlaceRep
            ,IRepository<WmsReceiptOrder, MasterDbContextLocator> wmsReceiptOrderRe
        )
        {
            _wmsOrderRep = wmsOrderRep;
            _sysDictTypeRep = sysDictTypeRep;
            _sysDictDataRep = sysDictDataRep;
            _sysExcelTemplateService = sysExcelTemplateService;
            _wmsOrderTypeRep = wmsOrderTypeRep;
            _wmsOrderDetailsRep = wmsOrderDetailsRep;
            _wmsPlaceRep = wmsPlaceRep;
            _wmsReceiptOrderRep = wmsReceiptOrderRe;
        }

        /// <summary>
        /// 报检上传
        /// </summary>
        /// <returns></returns>
        [HttpPost("InspectionDeclaration")]
        [AllowAnonymous]
        [UnifyResult(typeof(object))]
        public async Task<object> InspectionDeclaration([FromBody] InspectionDeclarationYiGo input)
        {
            try
            {
                
                //创建指定名称的订单操作
                string url = App.Configuration["YiGoWebApi:Qcnotice"];
                
                //input.Billdate =Convert.ToDateTime(input.Billdate.ToString("yyy-MM-dd"));
                //获取主单据
                //var wmsReceiptOrderModal = await _wmsReceiptOrderRep.FirstOrDefaultAsync(x => x.Id == input.Id);
                //if (wmsReceiptOrderModal == null) throw Oops.Oh("单据信息不存在!");
                input.WMSNO = "505005063098437";
                input.Billdate = DateTime.Now.ToString("yyyy-MM-dd");
                // 写日志文件
                //Log.Error($"[InspectionDeclaration][单据号:{wmsReceiptOrderModal.NO}][url:{url}]");

                var response = await url.SetHttpMethod(HttpMethod.Post)
                                        .SetBody(input, "application/json")
                                        .PostAsAsync<InspectionDeclarationOutput>();
                // 写日志文件
                //Log.Error($"[InspectionDeclaration][单据号:{wmsReceiptOrderModal.NO}][response:{response.ToJson()}]");

                return XnRestfulResultProvider.RESTfulResult(response);
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex.Message);
            }
        }

        /// <summary>
        /// 获取报检结果
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetInspectionResult")]
        [AllowAnonymous]
        [UnifyResult(typeof(object))]
        [UnitOfWork]
        public async Task<object> GetInspectionResult([FromBody] GetInspectionResultInput input)
        {
            try
            {
                //创建指定名称的订单操作
                string url = App.Configuration["YiGoWebApi:QueryRQC"];
                // 写日志文件
                Log.Error($"[InspectionDeclaration][单据号:{input.NO}][url:{url}]");

                var response = await url.SetHttpMethod(HttpMethod.Post)
                                        .SetBody(input, "application/json")
                                        .PostAsAsync<GetInspectionResultOutput>();
                // 写日志文件
                Log.Error($"[InspectionDeclaration][单据号:{input.NO}][response:{response.ToJson()}]");

                //获取结果后，合格生成入库单，测试阶段收货即可生成入库单
                return XnRestfulResultProvider.RESTfulResult();
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex.Message);
            }
        }

        /// <summary>
        /// 分页查询入库通知单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsOrderOutput>> Page([FromQuery] WmsOrderSearch input)
        {
            var wmsOrders = await _wmsOrderRep.DetachedEntities
                                     .Where(!string.IsNullOrEmpty(input.NO), u => EF.Functions.Like(u.NO, $"%{input.NO.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.SourceBillNo), u => EF.Functions.Like(u.SourceBillNo, $"%{input.SourceBillNo.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorcode), u => EF.Functions.Like(u.Vendorcode, $"%{input.Vendorcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Vendorname), u => EF.Functions.Like(u.Vendorname, $"%{input.Vendorname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Companyname), u => EF.Functions.Like(u.Companyname, $"%{input.Companyname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WarehouseKeepername), u => EF.Functions.Like(u.WarehouseKeepername, $"%{input.WarehouseKeepername.Trim()}%"))
                                     .Where(input.TradeMode != null, u => u.TradeMode == input.TradeMode)
                                     .Where(!string.IsNullOrEmpty(input.WarehouseCentername), u => EF.Functions.Like(u.WarehouseCentername, $"%{input.WarehouseCentername.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.StoreRoomname), u => EF.Functions.Like(u.StoreRoomname, $"%{input.StoreRoomname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.DeclarationCode), u => EF.Functions.Like(u.DeclarationCode, $"%{input.DeclarationCode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Majorname), u => EF.Functions.Like(u.Majorname, $"%{input.Majorname.Trim()}%"))
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsOrderSearch>(input))
                                     .ProjectToType<WmsOrderOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 获取单据明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("PageDetail")]
        public async Task<PageResult<WmsOrderDetailOutput>> PageDetail([FromQuery] PageDetailInput input)
        {
            var wmsOrders = await _wmsOrderDetailsRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<WmsOrderDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }
    }
}
